<?php
require_once 'admin-load.php';


$action = isset($_REQUEST['action']) ? $_REQUEST['action'] : 'index';



switch ($action) {
    case 'index':
        index();
        break;
    case 'add':
        add();
        break;
    case 'edit':
        edit();
        break;
    case 'view':
        view();
        break;
    case 'delete':
        delete();
        break;

}
/**
 * Index user
 * 
 * @global Twig_Environment $twig 
 */
function index() {
    global $twig, $dbp;
    
    $users = $dbp->get_results("SELECT * FROM users");
    
    echo $twig->render('user.html', array('users' => $users));
    
}
/**
 * Add new user
 * 
 * @global Twig_Environment $twig
 * @global ezSQL_mysql $dbp 
 */
function add() {
    global $twig, $dbp;
    if (isset($_POST['save']) && $_POST['save'] == 1) {
        $username = $dbp->escape($_POST['username']);
        $email = $dbp->escape($_POST['email']);
        $password = md5($_POST['password']);
        $firstname = $dbp->escape($_POST['first_name']);
        $lastname = $dbp->escape($_POST['last_name']);
        $created = date('Y-m-d h:i:s');
        
        $query = "INSERT INTO users(username, password, email, first_name, last_name, created) VALUES('$username', '$password', '$email', '$firstname', '$lastname', '$created')";
        if ($dbp->query($query)) {
            redirect(BASE_URL.'admin/user.php');
        }
        
    }
    echo $twig->render('user-add.html');
}

/**
 * Edit user
 * 
 * @global Twig_Environment $twig
 * @global ezSQL_mysql $dbp 
 */
function edit() {
    
    
    global $twig, $dbp;
    if (isset($_GET['user_id'])) {
        $id = intval($_GET['user_id']);
        $query = "SELECT * FROM users WHERE id =$id";
        $user = $dbp->get_row($query);
        echo $twig->render('user-edit.html', array('user' => $user));
    }

    if (isset($_POST['update']) && $_POST['update'] == 1) {
        $id = $_POST['user_id'];
        $username = $dbp->escape($_POST['username']);
        $email = $dbp->escape($_POST['email']);
        $password = md5($_POST['password']);
        $firstname = $dbp->escape($_POST['first_name']);
        $lastname = $dbp->escape($_POST['last_name']);
        $modified = date('Y-m-d h:i:s');
        $pass = $_POST['password'];
        $con_pass = $_POST['comfirm_password'];
        if ($pass == $con_pass) {
            $query = "UPDATE users SET username='$username',email='$email', password='$password',first_name='$firstname', last_name = '$lastname',modified='$modified' WHERE id =$id";
            if ($dbp->query($query)) {
                redirect(BASE_URL . 'admin/user.php');
            }
        }
    }
   
}
function delete() {
    global $twig, $dbp;
    $id = $_GET['user_id'];
    
    $delete = "DELETE FROM users WHERE id=$id";
    if($dbp->query($delete)){
        redirect (BASE_URL.'admin/user.php');
    }
}

?>
